package com.itjh.aop;

import com.alibaba.fastjson.JSONObject;
import com.itjh.mapper.OperateLogMapper;
import com.itjh.pojo.OperateLog;
import com.itjh.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;


/**
 * Description:
 *
 * @Create 2025/1/22 13:43
 */

@Slf4j
@Aspect
@Component
public class LogAspect {
    @Resource(name = "operateLogMapper")
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.itjh.annotaiton.Log)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {

        long begin = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        Map<String, Object> map = ThreadLocalUtils.getValue();
        Integer userId = Integer.valueOf(map.get("id").toString());
        //操作耗时
        Long costTime = end - begin;
        OperateLog operateLog = OperateLog.builder()
                .operateUser(userId)
                .operateTime(LocalDateTime.now())
                .className(pjp.getTarget().getClass().getName())
                .methodName(pjp.getSignature().getName())
                .methodParams(Arrays.toString(pjp.getArgs()))
                .returnValue(JSONObject.toJSONString(result))
                .costTime(costTime)
                .build();

        //记录日志
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志: {}" , operateLog);
//        ThreadLocalUtils.removeValue();
        return result;
    }
}
